<template>
    <div class="common-layout">
        <el-container>
          <el-header>
            <el-button size="small" type="primary" @click="handleAdd()">新增</el-button>
            <el-button size="small" type="success" @click="handleEdit(-1)">修改</el-button>
            <el-button size="small" type="danger" @click="handleDelete()">删除</el-button>
            <el-button size="small" type="success" @click="handleRefresh()">刷新</el-button>
            <el-button size="small" type="success"  @click="handleCopy()">复制</el-button>
            <el-button size="small" type="primary"   @click="handleQuery()">高级查询</el-button>
            <el-dropdown class="left-10">
                <el-button type="primary" size="small">
                    其他功能<el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="import_file()">Excel导入</el-dropdown-item>
                    <el-dropdown-item @click="viewStatus">审批详情</el-dropdown-item>
                    <el-dropdown-item @click="DownExcel=true">Excel导出</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
            </el-dropdown>
            <el-input v-model="fastSearch" class="left-10" style="width: 300px;" placeholder="快速查询" size="small"></el-input>
            <el-button size="small" class="left-10" @click="queryBuildShow='';getList(1)" type="primary">快速查询</el-button>
          </el-header>
          <el-main>
            <vxe-table border resizable size="mini" show-overflow keep-source :data="TableData[MainTable.tableName]"
            :ref="getStartRef" :name="MainTable.tableName" :row-config="{isCurrent: true, isHover: true}" @current-change="tableClick"  :toolbar-config="tableToolbar" :loading="loading"  :show-footer="ShowFooter" :footer-method="footerMethod">
                <vxe-column type="checkbox"  width="35"></vxe-column>
                <vxe-column field="RecordID" width="60" align="center"  title="ID"></vxe-column>
                <vxe-column field="StatusCode" width="70" align="center" title="审核状态"   type="html" v-if="verifyStatusCode" :formatter="formatStatus"></vxe-column>
                <vxe-column min-width="100"  v-for="item in Fields[MainTable.tableName]" :field="item.fieldName"  :visible="item.hidden===0"  :key="item.fieldID" :title="item.fieldDispName" :formatter="formatDate" :edit-render="{}" :sortable="item.orderby>0" >
                  <template #edit="{ row }">
                    <vxe-input v-model="row[item.fieldName]" type="text"></vxe-input>
                  </template>
                </vxe-column>
              </vxe-table>
              <vxe-pager size="mini" perfect :loading="MainPageLoading" :current-page="MainPage.pageNum" :page-size="MainPage.pageSize" :total="MainPage.totalResult" :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']" @page-change="MainPageChange">
                <template #left>
                      <vxe-button style="float: left !important;" status="primary" v-if="isequipment" @click="multiple">批量修改</vxe-button>
                </template>
              </vxe-pager>
          </el-main>
        </el-container>
        <vxe-modal :title="Add?'新增':'修改'" v-model="ShowEdit"  :show-zoom="isequipment"  class-name="editrow" resize remember fullscreen transfer destroy-on-close @close="handleRefresh">
          <el-container>
            <el-header>
              <el-button type="success" :disabled="saveDisabled" @click="Save()" size="small">保存</el-button>
              <el-dropdown class="left-10">
                <el-button type="primary" size="small">
                    加载命令<el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item><el-button type="primary" size="small">用记表</el-button></el-dropdown-item>
                  </el-dropdown-menu>
                </template>
            </el-dropdown>
            </el-header>
            <el-main>
              <templateEdit 
                :Fields="Fields" 
                :DataSource="AllData" 
                :MT="MainTable" 
                :DT="DetailTables" 
                :Combo="combo" 
                :Rules="rules" 
                :isequipment="isequipment" 
                :selectRules="SelectRules" 
                :isNew="Add" 
                ref="EditData"
              ></templateEdit>
            </el-main>
          </el-container>
        </vxe-modal>
        <!--查询窗口-->
        <vxe-modal title="查询" v-model="ShowQuery"  :show-zoom="isequipment?true:false"  ref="Query" resize remember width="800"  :before-hide-method="beforeHideMethod"  destroy-on-close transfer>
          <el-button-group>
            <el-button size="small" type="primary"  @click="QueryTable.insertAt({field:null,type:'=',value:null,relation:null}, -1)">添加</el-button>
            <el-button size="small" type="primary"  @click="QueryTable.remove()">清空</el-button> </el-button-group>
          <vxe-table border :height="heights" size="mini" :data="queryTable"  ref="QueryTable"  :edit-config="{trigger: 'click', mode: 'row'}">
            <vxe-column type="seq" width="40"></vxe-column>
            <vxe-column width="230"  field="field" title="字段" :cell-render="{}">
              <template #default="{ row }">
                <vxe-select v-model="row.field" placeholder="查询表字段" clearable transfer @change="changeField(row)" @blur="handleFindChange">
                  <vxe-optgroup v-for="(tb ,name) in queryFieldss" :label="tb.tableDispName" :key="name">
                    <vxe-option v-show="item.hidden===0" v-for="(item,index) in tb.Children" :key="index" :value="tb.tableName+'.'+item.fieldName" :label="tb.tableDispName+'.'+item.fieldDispName"></vxe-option>
                  </vxe-optgroup>
                </vxe-select>
              </template>
            </vxe-column>
            <vxe-column width="100" field="type"  title="条件" :cell-render="{}">
              <template #default="{ row }">
                <vxe-select v-model="row.type" placeholder="条件" clearable transfer>
                    <vxe-option v-for="(item,index) in Filter" :key="index" :value="item.type" :label="item.title"></vxe-option>
                </vxe-select>
              </template>
            </vxe-column>
            <vxe-column title="值" field="value" :cell-render="{}">
              <template #default="{ row }">
                <vxe-input v-if="row.tp!==4 && row.co===0 " v-model="row.value" type="text" @blur="handleFindChange"></vxe-input>
                <vxe-input v-if="row.tp===4 && row.co===0" v-model="row.value" type="date" transfer @blur="handleFindChange"></vxe-input>
                <vxe-pulldown v-if="row.co!==0" :ref="'querySelect'+row['_X_ID']" @blur="handleFindChange">
                  <template #default>
                    <vxe-input v-model="row.value" v-show="false"></vxe-input>
                    <vxe-input v-model="row.text" placeholder="搜索..." @focus="focusEvent2('querySelect'+row['_X_ID'],row['co'])" @keyup="keyupEvent2(row.text,row['co'])"></vxe-input>
                  </template>
                  <template #dropdown>
                    <vxe-list height="200" class="my-dropdown2" :data="Querylist" auto-resize>
                      <template #default="{ items }">
                        <div class="list-item2" v-for="item in items" :key="item.Value" @click="selectEvent2(item,row,'querySelect'+row['_X_ID'])">
                          <span>{{ item.Title }}</span>
                        </div>
                      </template>
                    </vxe-list>
                  </template>
                </vxe-pulldown>
              </template>
            </vxe-column>
            <vxe-column title="关联" field="relation" :cell-render="{}" >
              <template #default="{ row }">
                <vxe-select v-model="row.relation" transfer multiple clearable placeholder="多选时注意顺序!" >
                  <vxe-option v-for="(item,index) in Relation" :key="index" :value="item.type" :label="item.title"></vxe-option>
                </vxe-select>
              </template>
            </vxe-column>
            <vxe-column title="操作" width="65">
              <template #default="{ row }">
                <el-button type="primary" size="small" :icon="Delete" @click="QueryTable.remove(row)"></el-button>
              </template>
            </vxe-column>
          </vxe-table>
          
            <div>{{queryBuildShow}}</div>
            <div style="float: right;margin-top: 10px;">
              <el-button  type="primary" size="small" :icon="Check" @click="handleFindChange">验证</el-button>
              <el-button  type="primary" size="small" :icon="Check" @click=" handleFind">确认</el-button>
            </div>
        </vxe-modal>
        <!--批次操作-->
        <vxe-modal title="批次处理" v-model="ShowMultiple" width="640" >
          <div style="display: flex">
            <el-button size="small" type="primary"  @click="MultipleTable.insertAt({field:null,value:null}, -1)">添加</el-button>
            <el-input  size="small" placeholder="请输入内容" v-model="Multiple.RecordIDs">
              <template slot="prepend">修改记录ID</template>
            </el-input>
          </div>
          <vxe-table border :height="heights" size="mini" :data="Multiple.Data"  ref="MultipleTable"  :edit-config="{trigger: 'click', mode: 'row'}">
            <vxe-column type="seq" width="40"></vxe-column>
            <vxe-column width="230"  field="field" title="字段" :cell-render="{}">
              <template #default="{ row }">
                <vxe-select v-model="row.field" placeholder="表字段" clearable transfer @change="changeField(row)">
                  <vxe-optgroup v-for="(tb ,name) in queryFieldss" :label="tb.tableDispName" :key="name">
                    <vxe-option v-show="item.hidden===0" v-for="(item,index) in tb.Children" :key="index" :value="tb.tableName+'.'+item.fieldName" :label="tb.tableDispName+'.'+item.fieldDispName"></vxe-option>
                  </vxe-optgroup>
                </vxe-select>
              </template>
            </vxe-column>
            <vxe-column title="值" field="value" :cell-render="{}">
              <template #default="{ row }">
                <vxe-input v-if="row.tp!==4 && row.co===0 " v-model="row.value" type="text" ></vxe-input>
                <vxe-input v-if="row.tp===4 && row.co===0" v-model="row.value" type="date" transfer></vxe-input>
                <vxe-pulldown v-if="row.co!==0" :ref="'querySelect'+row['_X_ID']" >
                  <template #default>
                    <vxe-input v-model="row.value" v-show="false"></vxe-input>
                    <vxe-input v-model="row.text" placeholder="搜索..." @focus="focusEvent2('querySelect'+row['_X_ID'])" @keyup="keyupEvent2(row.text)"></vxe-input>
                  </template>
                  <template #dropdown>
                    <vxe-list height="200" class="my-dropdown2" :data="list2[row['co']]" auto-resize>
                      <template #default="{ items }">
                        <div class="list-item2" v-for="item in items" :key="item.Value" @click="selectEvent2(item,row,'querySelect'+row['_X_ID'])">
                          <span>{{ item.Title }}</span>
                        </div>
                      </template>
                    </vxe-list>
                  </template>
                </vxe-pulldown>
              </template>
            </vxe-column>
            <vxe-column title="操作" width="65">
              <template #default="{ row }">
                <el-button type="primary" size="small" icon="el-icon-delete" @click="MultipleTable.remove(row)"></el-button>
              </template>
            </vxe-column>
          </vxe-table>
        <template>
          <div style="float: right">
            <el-button  type="primary" size="small" icon="el-icon-check" @click="handleFindEditChange">确认</el-button>
          </div>
        </template>
      </vxe-modal>
      <!--导出Excel-->
      <vxe-modal title="导出Excel" v-model="DownExcel" width="440" >
        <template #default>
          <el-row   type="flex" class="row-bg" justify="center">
            <el-col :span="12">
              <el-button  type="primary" icon="el-icon-download" @click="down_file(0)">当前页选中记录({{startRef.getCheckboxRecords().length}}条)</el-button>
            </el-col>
            </el-row>
          <el-row   type="flex" class="row-bg" justify="center">
            <el-col :span="12">
              <el-button  type="primary" icon="el-icon-download" @click="down_file(1)">当前页所有记录({{startRef.getTableData().fullData.length}}条)</el-button>
            </el-col>
            </el-row>
          <el-row  v-if="RecordIDS.length>0" type="flex" class="row-bg" justify="center">
            <el-col :span="12">
              <el-button  type="primary" icon="el-icon-download" @click="down_file(2)">所有查询记录({{MainPage.totalResult}}条)</el-button>
            </el-col>
          </el-row>
          <el-row  v-if="DownFile.load" type="flex" class="row-bg" justify="center">
            <el-col :span="20" style="text-align: center;">
            <div><i class="el-icon-loading"></i>生成数据中.....</div>
            </el-col>
          </el-row>
          <el-row  v-if="DownFile.fileName.length>0" type="flex" class="row-bg" justify="center">
            <el-col :span="20" style="text-align: center;">
              <a :href="DownFile.url" rel="noopener" target="_blank" > {{DownFile.fileName}} 下载</a>
            </el-col>
          </el-row>
        </template>
      </vxe-modal>
    </div>
</template>

<script>
  import {ref,reactive,onBeforeMount,toRefs,getCurrentInstance,onMounted} from "vue"
  import { useRouter } from 'vue-router'
  import XEUtils from 'xe-utils'
  import templateEdit from "../components/templateEdit.vue"
  import { getCombo,listTemplate,delTemplate,getTemplate,getDataGrid,GetApproveStatus,downTemplate,importTemplate,addTemplate,editTemplate} from "/@/api/linkoo/form"
  import { ElMessage, ElMessageBox } from 'element-plus'
  import {Delete,Check} from '@element-plus/icons-vue'
  import VXETable from 'vxe-table'
  export default {
    components:{templateEdit},
      setup(props,ctx) {
        let router = useRouter()
        let loading=ref(false)
        let ShowFooter = ref(false)
        let fastSearch =ref('')
        let queryBuildShow=ref('')
        let RecordIDS=ref('')
        let verifyStatusCode=ref(false)
        let Add = ref(false)
        let heights = ref(300)
        let sendDingShow = ref(false)
        let ShowEdit = ref(false)
        let saveDisabled =ref(false)
        let ShowQuery=ref(false)
        let QueryTable = ref(null)
        let Query = ref(null)
        let MainPageLoading=ref(false)
        let ShowMultiple = ref(false)
        let DownExcel=ref(false)
        let state = reactive({
          MainTable:{},
          FooterFields:[],
          TableData: {},
          DetailTables: [],
          isequipment:true,
          template:{},
          Multiple: {Data:[],RecordIDs:''},
          rules:{},
          approveStatus:{},
          list2: { },
          combo:{},
          SelectRules:[],
          queryFieldss:{},
          queryFields:[],
          Fields: {},
          DetailPage: {},
          queryTable:[],
          DownFile:{'url':'','fileName':'',load:false},
          selectMainData: null,
          MainPage: { pageNum: 1, pageSize: 10, totalResult: 0 },
          AllData: {},
          tableToolbar:{perfect: true,refresh: true,zoom: true,custom: true},
          StatusCode:0,
          Relation:[{ type: 'or', title: '或' },{ type: 'and', title: '且' },{ type: '(', title: '(' },{ type: ')', title: ')' }],
          Filter:[{ type: '=', title: '等于' },{ type: '<>', title: '不等于' },{ type: '<', title: '小于' },{ type: '<=', title: '小于等于' },{ type: '>', title: '大于' },{ type: '>=', title: '大于等于'},{ type: 'like', title: '包含'},{ type: 'in', title: '在列表中'}],
        })
        onMounted(()=>{
          getInfo()
          if( navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i) ){
            state.isequipment=false;
          }
          else {
            state.isequipment=true
          }
        })
        const handleRefresh=()=> {
          fastSearch.value=''
          queryBuildShow.value=''
          resetData()
          getList(3)
        }
        const getInfo = ()=>{
          loading.value=true
          // heights.value=this.$parent.$el.clientHeight-100
          getTemplate("FYBXD").then(response => {
          if(response['code']===undefined){
            setTimeout(()=>{getInfo()},1000)
          }
          state.MainTable = response.data.table.filter(item => item.tableType === 0)[0]
          if(state.MainTable['onSheet']!==''){
            state.FooterFields=state.MainTable['onSheet'].split(',')
            ShowFooter.value=true
          }
          state.DetailTables = response.data.table.filter(item => item.tableType === 1)
          state.template = response.data.template
          state.rules=response.data.rules
          state.SelectRules=XEUtils.orderBy(XEUtils.toArray(response.data['selectRule']),'runSeq')
          let TB = {}
          response.data.table.forEach(row => {
            TB[row['tableID']] = row['tableName']
            state.TableData[row['tableName']] = []
            state.queryFieldss[row['tableName']] =row
            state.queryFieldss[row['tableName']]['Children']=[]
          })
          state.queryFields=response.data.fields
          XEUtils.orderBy(response.data.fields,[['tableID', 'asc'],['ob', 'asc'],['fieldID', 'asc']]).forEach(field => {
            state.queryFieldss[TB[field.tableID]]['Children'].push(field)
            if(field.componentID>0&&field.componentType===1){
              getCombo(field.componentID).then(res=>{
                console.log(JSON.stringify(res),field.componentID);
                let arr=res.data.list.map((item,index)=>{
                  return{label:item.content,value:item.value}
                })
                state.combo[field.fieldName]=arr
              })
            }
            if (state.Fields[TB[field.tableID]] === undefined) {
              state.Fields[TB[field.tableID]] = []
              state.DetailPage[TB[field.tableID]] = { currentPage: 1, pageSize: 10, totalResult: 0 }
            }
            
            state.Fields[TB[field.tableID]].push(field)
          })
          if (state.DetailTables.length>0){
              state.selectTab = state.DetailTables[0].tableName
              // heights.value=heights.value/2-35
            }
          if(state.template.dingProcID!==''){verifyStatusCode.value=true}
          loading.value = false
          getList(1)
        })
        }
        const getList=(types)=>{
          const query={pageNum: state.MainPage.pageNum,pageSize: state.MainPage.pageSize}
          if(!XEUtils.isEmpty(fastSearch.value)){
            query['QuickSearch']=fastSearch.value
          }
          if(queryBuildShow.value!==''){
            query['Search']=queryBuildShow.value
          }
          listTemplate("FYBXD", 0,query).then(response => {
             console.log(response,"pppp");
            XEUtils.objectEach(response.data,(item, key)=>{
              if (key === state.MainTable.tableName) {
                RecordIDS.value=item.RecordIDS
                if(types === 2 ){
                  state.AllData[key] = item.list[0]
                  state.selectMainData=item.list[0]
                  return
                }
              }
              state.TableData[key] = item.list===null?[]:item.list
              state.AllData[key] = state.TableData[key]
              startRef.value.reloadData(item.list)
            })
            console.log(query);
            if(types !== 2) {
              state.MainPage.totalResult=response.data[ state.MainTable.tableName].total
            }
          })
        }
        const formatStatus=({cellValue})=>{
          return cellValue===1?'<span class="S S1">审批中</span>':cellValue===2?'<span class="S S2">同意</span>':cellValue===3?'<span class="S S3">中止</span>':cellValue===4?'<span class="S S4">拒绝</span>':'未提交'
        }
        const formatDate=({cellValue,row,column})=>{
          let extend=XEUtils.toStringJSON(row['Extend'])
          if(extend[column.field]===null||extend[column.field]===undefined){
            extend[column.field]=cellValue?cellValue:''
          }
          return XEUtils.get(extend,column.field)
        }
        const footerMethod=({ columns, data })=>{
          return [
            columns.map((column, columnIndex) => {
              if (columnIndex === 1) {
                return '合计'
              }
              if (state.FooterFields.includes(column.property)) {
                return sumNum(data, column.property)
              }
              return null
            })
          ]
        }
        const sumNum = (list, field)=>{
          let count = 0
          list.forEach(item => {
            count += Number(item[field])
          })
          console.log(count);
          return count
        }
        const tableClick=()=> {
          state.selectMainData = startRef.value.getCurrentRecord()
          // getList(2)
          state.StatusCode=XEUtils.toInteger(state.selectMainData['StatusCode'])
            if(state.template.dingForms!==''&& state.StatusCode<1 && state.selectMainData.RecordID>0){
              sendDingShow.value=true
          }
        }
        // 新增
        const handleAdd=()=>{
          resetData()
          Add.value = true
          ShowEdit.value = true
          saveDisabled.value = false
        }
        const resetData=()=>{
          let Data = {}
          sendDingShow.value=false
          state.DetailTables.forEach(row => {
            Data[row.tableName] = []
            state.TableData[row.tableName] = []
          })
          // this.selectDetailData = Data
          state.selectMainData={}
          state.Fields[state.MainTable.tableName].forEach(row=>{
            state.selectMainData[row.fieldName] = ''
            if(row.fieldName==='Extend'){
              state.selectMainData[row.fieldName] = '{}'
            }
          })
          state.selectMainData['RecordID'] = 0
          Data[state.MainTable.tableName] =  state.selectMainData
          state.AllData=Data
        }
        // 获取动态refs，待测试
        let startRef = ref({})
        const getStartRef=(el)=>{
          if ((el && el.$attrs['name'] >= 0) || (el && el.$attrs['name'])) {
            startRef.value= el
            console.log('el', startRef.value)
          }
        }
        let EditData = ref(null)
        const Save = async()=>{
          saveDisabled.value=true
          let err=0
          const errMap= await EditData.value.startRef.value.validate().catch(errMap => errMap)
          if (errMap) {err++}
          for (const x in EditData.value.DT)  // x 为属性名
          {
            const tb=EditData.value.DT[x]
            if(isequipment.value){
              const errMap= await EditData.value.$refs[tb.tableName][0].validate().catch(errMap => errMap)
              if (errMap) {err++}
            }else{
              for (let i=0;i<EditData.value.DetailsData[tb.tableName].length;i++){
                const errMap= await EditData.value.$refs[tb.tableName+'_'+i][0].validate().catch(errMap => errMap)
                if (errMap) {err++}
              }
            }
          }
          if(err>0) {
            saveDisabled.value = false
            return false}
          const Data = {}
            Data['D'] =EditData.value.getDetailData()
            Data['M'] = EditData.value.getMainData()

            if (Add.value) {
              await addTemplate("FYBXD", Data).then(response => {
                if (response.code === 0) {
                  state.selectMainData.RecordID=response.data
                  state.selectMainData.StatusCode=0
                  sendDingShow.value=true
                  ElMessage({
                    message: '执行成功',
                    grouping: true,
                    type: 'success',
                  })
                }
                Add.value=false
              })
            } else {
              await editTemplate("FYBXD", state.selectMainData.RecordID, Data).then(response => {
                if (response.code === 0) {
                  ElMessage({
                    message: '执行成功',
                    grouping: true,
                    type: 'success',
                  })
                } else {
                  ElMessage({
                    message: response.msg,
                    grouping: true,
                    type: 'error',
                  })
                }
              })
            }

          EditData.value.SaveSuccess()
          //  this.ShowEdit = false
          // this.handleRefresh()
          saveDisabled.value = false
        }
        const handleEdit=()=>{
          state.selectMainData = startRef.value.getCheckboxRecords()
          if( state.selectMainData.length==0){
            ElMessage({
              message: '选择数据再修改',
              grouping: true,
              type: 'info',
            })
            return
          }
          Add.value = false
          ShowEdit.value = true
          saveDisabled.value = false
        }
        const handleDelete = ()=>{
          let $table = startRef.value
          const rows = $table.getCheckboxRecords()
          if (rows.length > 0) {
            ElMessageBox.confirm(
              '是否确认删除选中的这些数据项?',
              '警告',
              {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
              }
            ).then(()=>{
              delTemplate('FYBXD',state.MainTable.tableName, XEUtils.pluck(rows, 'RecordID')).then(response => {
                resetData()
                getList(1)
                ElMessage({
                  message: '删除成功',
                  grouping: true,
                  type: 'success',
                })
              })
            }).catch(()=>{})
          } else {
            ElMessage({
              type: 'info',
              message: '选择数据后再删除!',
            })
          }
        }
        const handleCopy=()=> {
          state.selectMainData = startRef.value.getCheckboxRecords()
          console.log(state.selectMainData.length);
          if(state.selectMainData.length==0){
            ElMessage({
              type: 'info',
              message: '选择数据再修改!',
            })
            return
          }
          Add.value = true
          ShowEdit.value = true
          saveDisabled.value = false
        }
        const handleQuery=()=>{
          if(state.queryTable.length===0){
            state.queryTable=[{field:null,type:'=',value:null,relation:null,tp:1,co:0}]
          }
          ShowQuery.value=true
        }
        const beforeHideMethod=()=>{
          state.queryTable=QueryTable.value.getTableData().fullData
        }
        const handleFindChange=()=>{
          const data= XEUtils.orderBy(QueryTable.value.getTableData().fullData, '_X_ID')
          let str=''
          for(let i=0;i<data.length;i++){
            const r=data[i]
            if(XEUtils.isEmpty(r.relation)&&data.length-i>1){
              ElMessage({
                type: 'info',
                message: '多条件之间缺少关联!',
              })
              return false
            }
            let value=''
            switch(r.type){
              case 'in':  value=  "('"+r.value.replaceAll(',',"','")+"')";break;
              case 'like':  value=  "'%"+r.value+"%'";break;
              default: value=  "'"+XEUtils.toValueString(r.value)+"'";break;
            }
            str += r.field+' '+r.type+' '+value+' '+XEUtils.toValueString(r.relation).replaceAll(',',' ')+' '
          }
          queryBuildShow.value=str
        }
        const handleFind=()=>{
          handleFindChange()
          getList(1)
          Query.value.close()
        }
        const changeField=(row)=>{
          row.value=null
          if(row.field===null)return
          const f=row.field.split(".")
          const field=state.Fields[f[0]].find(item=>item.fieldName===f[1])
          row.tp=field.dataTypeID
          row.co=field.componentType+field.componentID
          if(field.componentType===3){
            state.querySelect=[]
            const t=JSON.parse(field.componentFieldName)
            const data= {id: field.componentID, filter: field.componentFilterExpr, fastSearch: '',tid: field.componentType, pageNum: 1, pageSize:5000 }
            getDataGrid(data).then(response => {
              state.querySelect=response.data.list.map(row=>{
                row['Title']=row[t[field.fieldName]['t']]
                row['Value']=row[t[field.fieldName]['v']]
                return row
              })
              state.list2[row.co]= Object.assign([], state.querySelect)
            })
          }if(field.componentType===1){
            state.querySelect=[]
            const t=JSON.parse(field.componentFieldName)
            getCombo(field.componentID).then(res=>{
              state.querySelect=res.data.list.map((item,index)=>{
                return{Title:item.content,Value:item.value}
              })
              state.list2[row.co]= Object.assign([], state.querySelect)
            })
          }
        }
        const MainPageChange=({ currentPage, pageSize }) =>{
          state.MainPage.pageNum = currentPage
          state.MainPage.pageSize = pageSize
          state.selectMainData=null
          getList(1)
        }
        const multiple=()=>{
          let $table = startRef.value
          const rows = $table.getCheckboxRecords()
          if (rows.length === 0) {
            ElMessage({
                type: 'info',
                message: '请在表中选择要修改的主数据!',
              })
            return false
          }
          state.Multiple['RecordIDs']=XEUtils.pluck(rows, 'RecordID').join(',')
          ShowMultiple.value=true
        }
        let MultipleTable = ref(null)
        const handleFindEditChange=()=>{
          state.Multiple.Data= XEUtils.orderBy(MultipleTable.value.getTableData().fullData, '_X_ID')
          MultipleEdit("FYBXD",state.Multiple).then(res=>{
            if(res.code===0){
              this.msgSuccess(res.data)
              ElMessage({
                type: 'success',
                message: res.data,
              })
              ShowMultiple.value=false
              handleRefresh()
            }else{
              this.msgError(res.msg)
              ElMessage({
                type: 'info',
                message: res.msg,
              })
            }
          })
        }
        const import_file =()=>{
          VXETable.readFile().then((params)=>{
            const {files} = params
            console.log(files)
            if(files[0].name.indexOf(' ')>-1){
              ElMessage({
                type: 'error',
                message: "文件名不能含有空格,请修改文件名!",
              })
              return
            }
            let forms = new FormData()
            forms.append('upload-file', files[0])
            importTemplate("FYBXD",forms).then(res => {
              if(res.code!==0){
                this.msgError(res.msg)
                ElMessage({
                  type: 'success',
                  message: res.msg,
                })
              }
              getList(1)
            })
          })
        }
        const down_file = (t)=>{
          state.DownFile.load=true
          let RDS=''
          if(t===0){
            const data=startRef.value.getCheckboxRecords().map((row)=>{
              return row.RecordID
            })
            RDS=data.join(',')
          }else if(t===1){
            const data=startRef.value.getTableData().fullData.map((row)=>{
              return row.RecordID
            })
            RDS=data.join(',')
          }else{
            RDS=RecordIDS.value
          }
          if(XEUtils.isEmpty(RDS)){
            state.DownFile.load=false
            ElMessage({
                type: 'info',
                message: "下载数据不能为空!",
              })
            return false
          }
          downTemplate("FYBXD",RDS).then(res=>{
            state.DownFile.load=false
            state.DownFile['url']=res.data.url
            state.DownFile['fileName']=res.data.fileName
          })
        }
        let showStatus =ref(false)
        const viewStatus = ()=>{
          console.log(state.selectMainData,"0987654321");
          if(state.selectMainData){
            GetApproveStatus(state.template.templateID,state.selectMainData.RecordID).then(res=>{
              state.approveStatus=res.data.info
              state.approveStatus['表单内容']= JSON.stringify(state.approveStatus['表单内容'],null,"\t")
              state.approveStatus['原始内容']= JSON.stringify(state.approveStatus['原始内容'],null,"\t")
              showStatus.value=true
            })
          }else{
            ElMessage({
                type: 'info',
                message: "选中记录后再操作!",
              })
          }
        }
        return{
          loading,
          ShowFooter,
          fastSearch,
          queryBuildShow,
          RecordIDS,
          verifyStatusCode,
          MultipleTable,
          startRef,
          heights,
          sendDingShow,
          ShowEdit,
          saveDisabled,
          Add,
          ShowQuery,
          QueryTable,
          Query,
          MainPageLoading,
          ShowMultiple,
          DownExcel,
          showStatus,
          EditData,
          getStartRef,
          ...toRefs(state),
          getInfo,
          getList,
          formatStatus,
          formatDate,
          sumNum,
          viewStatus,
          footerMethod,
          tableClick,
          handleAdd,
          resetData,
          handleRefresh,
          Save,
          handleEdit,
          handleDelete,
          handleCopy,
          handleQuery,
          beforeHideMethod,
          handleFindChange,
          handleFind,
          changeField,
          multiple,
          MainPageChange,
          handleFindEditChange,
          import_file,
          down_file,
          Delete,
          Check
        }
      }
  }
</script>

<style scoped>
.el-header{
        padding: 0;
        height: 40px;
    }
    .el-main{
        border-radius: 5px;
        height: 100vh;
        padding: 0;
    }
    .left-10{
        margin-left: 10px;
    }
    .S{line-height: 36px;  padding: 10px 25px;  margin: -20px;}
    .S1{background-color: #409eff;color: #fff}
    .S2{background-color: #85ce61;color: #fff}
    .S3{background-color: #909399;color: #fff}
    .S4{background-color: #f56c6c;color: #fff}
</style>